package com.thinkgem.jeesite.common.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 工具辅助类
 * 
 * @author zhangxvle
 * @date 2015-10-10
 */
public class HJBUT {
	private static Log logger = LogFactory.getLog("exceptionLog");

	public static DateFormat df_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static DateFormat df_file_time = new SimpleDateFormat("yyyyMMddHHmmss");
	public static DateFormat df_day = new SimpleDateFormat("yyyy-MM-dd");
	public static DateFormat df_day_new = new SimpleDateFormat("yyyyMMdd");
	public static DecimalFormat df = new DecimalFormat("0.00");
	public static Pattern int_pattern = Pattern.compile("[0-9]*");
	public static char[] codeSequence = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };

	public static String eL0 = "([0-9]{4})[年/.-]([0-9]{1,2})[月/.-]([0-9]{1,2})日?[\\s\\S]{0,15}([0-9]{2}:[0-9]{2}:[0-9]{2})";
	public static String eL1 = "([0-9]{4})[年/.-]([0-9]{1,2})[月/.-]([0-9]{1,2})日?[\\s\\S]{0,15}([0-9]{1}:[0-9]{2}:[0-9]{2})";
	public static String eL2 = "([0-9]{4})[年/.-]([0-9]{1,2})[月/.-]([0-9]{1,2})日?[\\s\\S]{0,15}([0-9]{2}:[0-9]{2})";
	public static String eL3 = "([0-9]{4})[年/.-]([0-9]{1,2})[月/.-]([0-9]{1,2})日?[\\s\\S]{0,15}([0-9]{1}:[0-9]{2})";
	public static String eL4 = "([0-9]{4})[年/.-]([0-9]{1,2})[月/.-]([0-9]{1,2})日?";
	public static String eL5 = "([0-9]{2})[年/.-]([0-9]{1,2})[月/.-]([0-9]{1,2})日?";

	public static String eL7 = "([0-9]{1,2})分钟前";
	public static String eL8 = "([0-9]{1,2})小时前";
	public static String eL9 = "([0-9]{1,2})天前";

	public static Pattern pd0 = Pattern.compile(eL0);
	public static Pattern pd1 = Pattern.compile(eL1);
	public static Pattern pd2 = Pattern.compile(eL2);
	public static Pattern pd3 = Pattern.compile(eL3);
	public static Pattern pd4 = Pattern.compile(eL4);
	public static Pattern pd5 = Pattern.compile(eL5);

	public static Pattern pd7 = Pattern.compile(eL7);
	public static Pattern pd8 = Pattern.compile(eL8);

	public static Pattern pd9 = Pattern.compile(eL9);
	
	public static String randStr ="123456789abcdefghjklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";

	public static void p(Object o) {
		System.out.println(o);
	};

	public static void log(Object o) {
		System.out.println(o);
	};

	public static String getDoubleString(double d) {
		return df.format(d);
	};

	public static double doubled(String d) {
		return Double.parseDouble(d);
	};

	public static double formatDouble(double d) {
		String temp = getDoubleString(d);
		return Double.parseDouble(temp);
	};

	public static int passMin(String time) {
		int min = 0;
		try {
			Date date = df_time.parse(time);
			long diff = new Date().getTime() - date.getTime();
			long m = diff / (1000 * 60);
			min = (int) m;
		} catch (ParseException e) {

			// e.printStackTrace();
			return min;
		} // 转换成功的Date对象
		return min;
	};

	public static int passMin(String time1, String time2) {
		int min = 0;
		try {
			Date date1 = df_time.parse(time1);
			Date date2 = df_time.parse(time2);
			long diff = date2.getTime() - date1.getTime();
			long m = diff / (1000 * 60);
			min = (int) m;
		} catch (ParseException e) {

			// e.printStackTrace();
			return min;
		} // 转换成功的Date对象
		return min;
	};

	/**
	 * 比较2个日期的大小
	 * 
	 * @param date_1
	 * @param date_2
	 * @return
	 */
	public static int passDay(String date_1, String date_2) {
		int min = 0;
		try {
			Date date1 = df_day.parse(date_1);
			Date date2 = df_day.parse(date_2);
			long diff = date2.getTime() - date1.getTime();
			long m = diff / (1000 * 60 * 60 * 24);
			min = (int) m;
		} catch (ParseException e) {

			// e.printStackTrace();
			return min;
		} // 转换成功的Date对象
		return min;
	};

	/**
	 * 获取当前系统时间 字符串的格式�? �? yyyy-MM-dd HH:mm:ss
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String currentTime() {
		return df_time.format(new Date());
	};

	public static String currentFileTime() {
		return df_file_time.format(new Date());
	};

	/**
	 * 获取当前系统日期 字符串的格式�? �? yyyy-MM-dd
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String currentDate() {
		return df_day.format(new Date());
	};
	
	public static int getCurrentDate() {
		String dayStr = df_day_new.format(new Date());
		return Integer.parseInt(dayStr);
	};

	/**
	 * 获取当前系统日期 字符串的格式�? �? yyyy-MM-dd
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String currentYear() {
		return df_day.format(new Date()).substring(0, 4);
	};

	/**
	 * 获取与当前日期相差i天的日期
	 * 
	 * @param i
	 *            相差天数
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String currentYear(int i) {
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		// 设置代表的日期为1�?
		c.set(Calendar.YEAR, year + i);
		return df_day.format(c.getTime()).substring(0, 4);
	};

	/**
	 * 获取当前系统日期 字符串的格式�? �? yyyy-MM-dd
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String currentMonth() {
		return df_day.format(new Date()).substring(0, 7);// 2011-12-07
	};

	public static String currentMonth(int i) {
		Calendar c = Calendar.getInstance();
		int month = c.get(Calendar.MONTH);
		// 设置代表的日期为1�?
		c.set(Calendar.MONTH, month + i);
		return df_day.format(c.getTime()).substring(0, 7);
	};

	public static String currentMonth(String this_month, int i) {
		Date date;
		Calendar c = Calendar.getInstance();
		try {
			date = df_day.parse(this_month + "-01");
			c.setTime(date);
			int month = c.get(Calendar.MONTH);
			c.set(Calendar.MONTH, month + i);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return df_day.format(c.getTime()).substring(0, 7);
	};

	public static int passMonth(String start, String end) {
		Date date_start;
		Date date_end;
		int pass = 0;
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();

		try {
			date_start = df_day.parse(start + "-01");
			date_end = df_day.parse(end + "-01");
			c1.setTime(date_start);
			c2.setTime(date_end);
		} catch (ParseException e) {

			e.printStackTrace();
		}
		while (c1.compareTo(c2) < 0) {
			log("pass=" + pass);
			pass++;
			c1.add(Calendar.MONTH, 1);// 开始日期加一个月直到等于结束日期为止
		}
		return pass;
	}

	/**
	 * 比较2个日期的大小
	 * 
	 * @param start
	 * @param end
	 * @return
	 */
	public static boolean dateCompare(String start, String end) {
		Date date_start;
		Date date_end;
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();

		try {
			date_start = df_day.parse(start);
			date_end = df_day.parse(end);
			c1.setTime(date_start);
			c2.setTime(date_end);
		} catch (ParseException e) {

			e.printStackTrace();
		}
		if (c1.compareTo(c2) > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 获取当前系统日期 字符串的格式�? �? yyyy-MM-dd
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String currentDay() {
		return currentDate().substring(8, 10);
	};

	public static String currentDay(int i) {
		return currentDate(i).substring(8, 10);
	};

	/**
	 * 获取指定返回格式的当前系统日�?
	 * 
	 * @param str
	 *            日期格式字符�?
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String currentDate(String str) {
		DateFormat _df = new SimpleDateFormat(str);
		return _df.format(new Date());
	};

	/**
	 * 获取与当前日期相差i天的日期
	 * 
	 * @param i
	 *            相差天数
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String currentDate(int i) {
		Calendar c = Calendar.getInstance();
		int day = c.get(Calendar.DATE);
		// 设置代表的日期为1�?
		c.set(Calendar.DATE, day + i);
		return df_day.format(c.getTime());
	};

	/**
	 * 获取与当前日期相差i天的日期
	 * 
	 * @param i
	 *            相差天数
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String currentDate(String date, int i) {
		Date day;
		Calendar c = Calendar.getInstance();
		try {
			day = df_day.parse(date);
			c.setTime(day);
		} catch (ParseException e) {

			e.printStackTrace();
		}
		int n = c.get(Calendar.DATE);
		// 设置代表的日期为1�?
		c.set(Calendar.DATE, n + i);
		return df_day.format(c.getTime());
	};

	/**
	 * 获取与当前日期相差i天的日期
	 * 
	 * @param i
	 *            相差天数
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String getTimeAfterMimute(String time, int i) {
		Date day;
		Calendar c = Calendar.getInstance();
		try {
			day = df_time.parse(time);
			c.setTime(day);
		} catch (ParseException e) {

			e.printStackTrace();
		}
		int n = c.get(Calendar.MINUTE);
		c.set(Calendar.MINUTE, n + i);
		return df_time.format(c.getTime());
	};

	/**
	 * 获取本月的第�?�?
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String firstDayOfMonth() {
		Calendar c = Calendar.getInstance();
		// 设置代表的日期为1�?
		c.set(Calendar.DATE, 1);
		return df_day.format(c.getTime());
	};

	/**
	 * 获取本月的最后一�?
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static int daysOfMonth(String day) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		try {
			Date date = sdf.parse(day);
			c.setTime(date);
		} catch (ParseException e) {

			e.printStackTrace();
			return 0;
		}
		// 获得当前月的�?大日期数
		int maxDay = c.getActualMaximum(Calendar.DATE);
		return maxDay;
	};

	/**
	 * 获取本月的最后一�?
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static int daysOfWeek(String day) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		try {
			Date date = sdf.parse(day);
			c.setTime(date);
		} catch (ParseException e) {

			e.printStackTrace();
			return 0;
		}
		// 获得当前月的�?大日期数
		int dayofweek = c.get(Calendar.DAY_OF_WEEK) - 1;
		if (dayofweek == 0) {
			dayofweek = 7;
		}
		;
		return dayofweek;
	};

	// 获取两个日期之间的天数
	public static int daysBetween(String smdate, String bdate) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		Date date1 = new Date();
		try {
			date = sdf.parse(smdate);
			date1 = sdf.parse(bdate);
		} catch (ParseException e) {

			e.printStackTrace();
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		long time1 = cal.getTimeInMillis();
		cal.setTime(date1);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	/**
	 * 获取本月的最后一�?
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String lastDayOfMonth() {
		Calendar c = Calendar.getInstance();
		// 获得当前月的�?大日期数
		int maxDay = c.getActualMaximum(Calendar.DATE);
		c.set(Calendar.DATE, maxDay);
		return df_day.format(c.getTime());
	};

	/**
	 * 获取�?�?7年的字符串数�?
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String[] lastSevenYears() {
		String[] years = new String[7];
		Calendar c = Calendar.getInstance();
		// 获得当前月的�?大日期数
		int curr_year = c.get(Calendar.YEAR);
		years[0] = String.valueOf(curr_year - 3);
		years[1] = String.valueOf(curr_year - 2);
		years[2] = String.valueOf(curr_year - 1);
		years[3] = String.valueOf(curr_year);
		years[4] = String.valueOf(curr_year + 1);
		years[5] = String.valueOf(curr_year + 2);
		years[6] = String.valueOf(curr_year + 3);
		return years;
	};

	/**
	 * 判断字符串是否为�?
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static boolean isEmpty(Object str) {
		if (str == null || "".equals(str.toString().trim()) || "-".equals(str.toString().trim())) {
			return true;
		}
		return false;
	}

	/**
	 * 返回前台的成功信息的json字符�?
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String suc(String str) {

		String s = "";
		if (str != null) {
			s = str;
		}
		return "{\"success\":\"true\",\"msg\":\"" + s + "\"}";
	}

	/**
	 * 返回前台的成功信息的json字符�?
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String suc(String str, String key, String value) {

		String s = "";
		if (str != null) {
			s = str;
		}
		return "{\"success\":\"true\",\"msg\":\"" + s + "\",\"" + key + "\":\"" + value + "\"}";
	}

	/**
	 * 返回前台的成功信息的json字符�?
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String suc(String str, String k1, String v1, String k2, String v2) {

		String s = "";
		if (str != null) {
			s = str;
		}
		return "{\"success\":\"true\",\"msg\":\"" + s + "\",\"" + k1 + "\":\"" + v1 + "\",\"" + k2 + "\":\"" + v2
				+ "\"}";
	}

	/**
	 * 返回前台的成功信息的json字符�?
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String suc(String str, String k1, String v1, String k2, String v2, String k3, String v3, String k4,
			String v4) {

		String s = "";
		if (str != null) {
			s = str;
		}
		return "{\"success\":\"true\",\"msg\":\"" + s + "\",\"" + k1 + "\":\"" + v1 + "\",\"" + k2 + "\":\"" + v2
				+ "\",\"" + k3 + "\":\"" + v3 + "\",\"" + k4 + "\":\"" + v4 + "\"}";
	}

	/**
	 * 返回前台的成功信息的json字符�?
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String suc(String str, String k1, String v1, String k2, String v2, String k3, String v3, String k4,
			String v4, String k5, String v5) {

		String s = "";
		if (str != null) {
			s = str;
		}
		return "{\"success\":\"true\",\"msg\":\"" + s + "\",\"" + k1 + "\":\"" + v1 + "\",\"" + k2 + "\":\"" + v2
				+ "\",\"" + k3 + "\":\"" + v3 + "\",\"" + k4 + "\":\"" + v4 + "\",\"" + k5 + "\":\"" + v5 + "\"}";
	}

	/**
	 * 返回前台的失败信息的json字符�?
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String err(String str) {

		String s = "";
		if (str != null) {
			s = str;
		}
		return "{\"success\":\"false\",\"msg\":\"" + s + "\"}";
	}

	public static String err(String str, String key, String value) {

		String s = "";
		if (str != null) {
			s = str;
		}
		return "{\"success\":\"false\",\"msg\":\"" + s + "\",\"" + key + "\":\"" + value + "\"}";
	}

	public static String err(String str, String k1, String v1, String k2, String v2) {

		String s = "";
		if (str != null) {
			s = str;
		}
		return "{\"success\":\"false\",\"msg\":\"" + s + "\",\"" + k1 + "\":\"" + v1 + "\",\"" + k2 + "\":\"" + v2
				+ "\"}";
	}

	public static String lpad(String str, int length) {
		return lpad(str, length, ' ');
	}

	public static String rpad(String str, int length) {
		return rpad(str, length, ' ');
	}

	public static String lpad(String str, int length, char dot) {

		int size = str.getBytes().length;
		if (size == length)
			return str;
		if (size > length) {
			return str;
		}
		int n = length - size;
		char[] dots = new char[n];
		for (int i = 0; i < n; i++) {
			dots[i] = dot;
		}
		return String.valueOf(dots) + str;
	}

	public static String rpad(String str, int length, char dot) {
		int size = str.getBytes().length;
		if (size == length)
			return str;
		if (size > length) {
			return str;
		}
		int n = length - size;
		char[] dots = new char[n];
		for (int i = 0; i < n; i++) {
			dots[i] = dot;
		}
		return str + String.valueOf(dots);
	}

	public static String readTxt(String path) {
		StringBuffer sb = new StringBuffer();
		try {
			String encoding = "UTF-8";
			File file = new File(path);
			if (true) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					sb.append(lineTxt);
				}
				read.close();
			}
		} catch (Exception e) {
			System.out.println("文件读取出错  path = " + path);
			e.printStackTrace();
		}
		return sb.toString();
	}

	public static String readTxt(File file) {
		StringBuffer sb = new StringBuffer();
		try {
			String encoding = "UTF-8";
			if (file != null && file.exists() && file.getName().toLowerCase().endsWith(".txt")) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					// log.info(new String(lineTxt.getBytes("UTF-8"),"GBK"));
					sb.append(lineTxt);
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件:" + file.getPath() + ", 或者不是txt文件 ");
			}
		} catch (Exception e) {
			System.out.println("文件读取出错  path = " + file.getPath());
			e.printStackTrace();
		}
		return sb.toString();
	}

	public static String readTxt2(File file) {
		StringBuffer sb = new StringBuffer();
		try {
			if (file != null && file.exists() && file.getName().toLowerCase().endsWith(".txt")) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file));// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					// log.info(new String(lineTxt.getBytes("UTF-8"),"GBK"));
					sb.append(lineTxt);
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件:" + file.getPath() + ", 或者不是txt文件 ");
			}
		} catch (Exception e) {
			System.out.println("文件读取出错  path = " + file.getPath());
			e.printStackTrace();
		}
		return sb.toString();
	}

	public static String readTxt(File file, String encoding) {
		StringBuffer sb = new StringBuffer();
		try {
			if (file != null && file.exists() && file.getName().toLowerCase().endsWith(".txt")) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					// log.info(new String(lineTxt.getBytes("UTF-8"),"GBK"));
					sb.append(lineTxt);
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件:" + file.getPath() + ", 或者不是txt文件 ");
			}
		} catch (Exception e) {
			System.out.println("文件读取出错  path = " + file.getPath());
			e.printStackTrace();
		}
		return sb.toString();
	}

	public static void copyFile(String oldPath, String newPath) {
		try {
			System.out.println(" copyFile    oldPath  =  " + oldPath);
			File oldfile = new File(oldPath);
			File file = new File(newPath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
				System.out.println(" 创建文件夹成功    mkdirs  =  " + file.getParentFile().getPath());
			}
			if (oldfile.exists()) { // 文件存在时
				BufferedInputStream inBuff = null;
				BufferedOutputStream outBuff = null;
				try {
					// 新建文件输入流并对它进行缓冲
					inBuff = new BufferedInputStream(new FileInputStream(oldfile));
					// 新建文件输出流并对它进行缓冲
					outBuff = new BufferedOutputStream(new FileOutputStream(file));
					// 缓冲数组
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = inBuff.read(b)) != -1) {
						outBuff.write(b, 0, len);
					}
					// 刷新此缓冲的输出流
					outBuff.flush();
				} finally {
					// 关闭流
					if (inBuff != null)
						inBuff.close();
					if (outBuff != null)
						outBuff.close();
				}
				//
				//
				//
				// InputStream inStream = new FileInputStream(oldPath); //读入原文件
				// OutputStream fs = new FileOutputStream(file);
				// byte[] buffer = new byte[1024];
				// int byteread = -1;
				// while ( (byteread = inStream.read(buffer)) != -1) {
				// fs.write(buffer);
				// }
				// fs.flush();
				// fs.close();
				// inStream.close();
			}
		} catch (Exception e) {
			System.out.println("复制单个文件操作出错");
			e.printStackTrace();
		}
	}

	public static String EncodeHtml(String content) {
		if (content == null)
			return "";
		String html = content;
		html = html.replaceAll("'", "&apos;");
		html = html.replaceAll("\"", "&quot;");
		html = html.replaceAll("\t", "&nbsp;&nbsp;");// 替换跳格
		// html = html.replaceAll(" ", "&nbsp;");// 替换空格
		html = html.replaceAll("<", "&lt;");
		html = html.replaceAll(">", "&gt;");
		return html;

	}

	private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
	private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
	private static final String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
	private static final String regEx_space = "\\s*|\t|\r|\n";// 定义空格回车换行符

	public static String delHTMLTag(String htmlStr) {
		Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(htmlStr);
		htmlStr = m_script.replaceAll(""); // 过滤script标签

		Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(htmlStr);
		htmlStr = m_style.replaceAll(""); // 过滤style标签

		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(htmlStr);
		htmlStr = m_html.replaceAll(""); // 过滤html标签

		Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);
		Matcher m_space = p_space.matcher(htmlStr);
		htmlStr = m_space.replaceAll(""); // 过滤空格回车标签
		return htmlStr.trim(); // 返回文本字符串
	}

	public static String getTextFromHtml(String htmlStr) {
		htmlStr = delHTMLTag(htmlStr);
		htmlStr = htmlStr.replaceAll("&nbsp;", "");
		// htmlStr = htmlStr.substring(0, htmlStr.indexOf("。")+1);
		return htmlStr;
	}

	/**
	 * 生成12位随机数字
	 * 
	 * @return
	 */
	public static String createCode() {
		// 生成随机数
		String code = null;
		Random random = new Random();
		StringBuffer randomCode = new StringBuffer();
		for (int i = 0; i < 12; i++) {
			String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
			randomCode.append(strRand);
		}
		code = randomCode.toString();
		return code;
	}

	/**
	 * 通过网站域名URL获取该网站的源码
	 * 
	 * @param url
	 * @return String
	 * @throws Exception
	 */
	public static String getURLSource(URL url, String encode) {

		StringBuffer contentBuffer = new StringBuffer();
		if (HJBUT.isEmpty(encode)) {
			encode = "gbk";
		}
		if ("auto".equals(encode)) {
			encode = "gbk";
		}
		int responseCode = -1;
		HttpURLConnection con = null;
		try {

			con = (HttpURLConnection) url.openConnection();
			con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:6.0) Gecko/20100101 Firefox/6.0");
			con.setRequestProperty("Cookie",
					"__jsluid=29a2ab4006c0d565b9742fb431b50b7d; __jsl_clearance=1456469569.356|0|C2wiiclSF7UZPMrkL8n8wbkjhZk%3D; JSESSIONID=00005OQLchcpGfnT5w98HaVVqde:-1; _gscu_1997809816=56469573sm0z9x15; _gscs_1997809816=56469573fsuiju15|pv:2; _gscbrs_1997809816=1");
			con.setRequestProperty("Connection", "keep-alive");
			con.setRequestProperty("X-Requested-With", "XMLHttpRequest");
			con.setRequestProperty("Host", "www.cbrc.gov.cn");
			con.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.5");
			con.setConnectTimeout(15 * 1000);
			con.setReadTimeout(15 * 1000);

			// 获得网页返回信息码
			responseCode = con.getResponseCode();
			if (responseCode == -1) {
				logger.info("信息：断线链接 " + "; 地址:" + url);
				con.disconnect();
				return "";
			}
			if (responseCode == 404) // 请求失败
			{
				System.err.println("请求404...");
				logger.info("信息：Not Found 无法找到指定位置的资源" + "; 地址:" + url);
				con.disconnect();
				return "";
			} else if (responseCode == 400) {
				logger.info("信息：Bad Request 请求出现语法错误" + "; 地址:" + url);
				con.disconnect();
				return "";
			} else if (responseCode == 401) {

				logger.info("信息：Unauthorized 客户试图未经授权访问受密码保护的页面" + "; 地址:" + url);
				con.disconnect();
				return "";
			} else if (responseCode == 403) {

				logger.info("信息：Forbidden 资源不可用" + "; 地址:" + url);
				con.disconnect();
				return "";
			} else if (responseCode == 500) {

				logger.info("信息：Internal Server Error 服务器遇到了意料不到的情况" + "; 地址:" + url);
				con.disconnect();
				return "";
			} else if (responseCode == 505) {

				logger.info("信息：服务器不支持请求中所指明的HTTP版本" + "; 地址:" + url);
				con.disconnect();
				return "";
			}
			InputStream inStr = con.getInputStream();
			InputStreamReader istreamReader = new InputStreamReader(inStr, encode);
			BufferedReader buffStr = new BufferedReader(istreamReader);
			String str = null;
			while ((str = buffStr.readLine()) != null)
				contentBuffer.append(str + "\n");
			inStr.close();
		} catch (IOException e) {
			logger.info("信息:" + e.toString() + "; 地址:" + url);
		} finally {
			con.disconnect();
		}

		return contentBuffer.toString().replace("\r\n", "").replace("\n", "").replace("\r", "");
	}

	/**
	 * 当前毫秒数与传入分钟数之差
	 * 
	 * @return
	 */
	public static String calcMillis(long nowMillis, long minis) {
		long calcmillis = 0;
		String retmillis = null;
		calcmillis = nowMillis - (minis * 60000);
		retmillis = String.valueOf(calcmillis);
		return retmillis;
	}

	/**
	 * 获取当前时间毫秒数
	 * 
	 * @return
	 */
	public static long currentMillis() {
		return System.currentTimeMillis();
	}

	/**
	 * 拼装上传服务器路径 部委ID/年/月/日/html||other/attachment/
	 * 
	 * @param govid
	 * @param type
	 * @param isatt
	 * @return
	 */
	public static String getUploadPath(String type, boolean isatt) {
		StringBuffer uploadpath = new StringBuffer();
		uploadpath.append("/");
		uploadpath.append(HJBUT.currentYear());
		uploadpath.append("/");
		uploadpath.append(HJBUT.currentMonth());
		uploadpath.append("/");
		uploadpath.append(HJBUT.currentDay());
		uploadpath.append("/");
		if ("html".equals(type)) {
			uploadpath.append(type);
			uploadpath.append("/");
		} else {
			uploadpath.append("other/");
		}
		if (isatt)
			uploadpath.append("attachment/");
		return uploadpath.toString();
	}

	/**
	 * 通过传入的格式格式化日期
	 * 
	 * @param date
	 * @param fmt
	 * @return
	 */
	public static String formatDateStr(String date, String fmt) {
		String newdate = null;
		if (StringUtils.isBlank(date) || "null".equals(date))
			return newdate;
		try {
			DateFormat df = new SimpleDateFormat(fmt);
			Date d = df.parse(date);
			newdate = df.format(d);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return newdate;
	}

	/**
	 * 截取字符串 截取前10，后6字
	 * 
	 * @param content
	 * @return
	 */
	public static String cutStr(String content) {
		if (StringUtils.isNotBlank(content) && content.length() > 20) {
			content = content.substring(0, 10) + "..." + content.substring(content.length() - 6, content.length());
		}
		return content;
	}

	/**
	 * 获取登录ID rd_6位字母数字随机组合
	 * 
	 * @author Jason.Qu
	 * @param length
	 * @return
	 */

	public static String getInvitaCode(int length) {

		String val = "";

		Random random = new Random();
		for (int i = 0; i < length; i++) {
			String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字

			if ("char".equalsIgnoreCase(charOrNum)) // 字符串
			{
				int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母
				val += (char) (choice + random.nextInt(26));
			} else if ("num".equalsIgnoreCase(charOrNum)) // 数字
			{
				val += String.valueOf(random.nextInt(10));
			}
		}
			return val;

	}

	/**
	 * 获取验证码 6位随机数字
	 * 
	 * @author Jason.Qu
	 * @param length
	 * @return
	 */
	public static String getValidCode(int length) {
		String val = "";
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			val += String.valueOf(random.nextInt(10));
		}
		return val;
	}

	/**
	 * 获取传入时间间隔N分钟后时间 字符串的格式�? �? yyyy-MM-dd HH:mm:ss
	 * 
	 * @param
	 * @return add time �?2011-10-07 modify time �?2011-10-07
	 */
	public static String calcTime(String time, int i) {
		String nowTime = null;
		try {
			Date date = df_time.parse(time);
			long currentTime = date.getTime() + i * 60 * 1000;
			Date newdate = new Date(currentTime);
			nowTime = df_time.format(newdate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return nowTime;
	};

	/**
	 * 校验传入参数是否为合法日期格式
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isValidDate(String str) {
		boolean convertSuccess = true;
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		try {
			format.setLenient(false);
			format.parse(str);
		} catch (ParseException e) {
			// e.printStackTrace();
			convertSuccess = false;
		}
		return convertSuccess;
	}
	
	/**
	 * 随机生成字符串
	 * @param length
	 * @return
	 */
	public static String getRandomCode(int length){
		
		String randomStr = "";
		for (int i = 0; i < length; i++) 
	    { 
	        int rand = (int) (Math.random() * randStr.length()); 
	        randomStr += randStr.charAt(rand); 
	    } 
		return randomStr;
	}

	public static void main(String[] args) {
	}

}
